package dao;

import dao.base.BaseDao;
import model.Article;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;


public class ArticleDao extends BaseDao<Article> {
    public ArticleDao(Class aClass) {
        super(Article.class);
    }

    private JdbcTemplate jdbcTemplate;

    public List<Article> findPage(String title, Integer startIndex, Integer pageSize){
        try {
            String sql = "select * from article where title like ? order by publish_date desc limit ?,?";
            jdbcTemplate = getJdbcTemplate();
            return jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Article.class),
                    "%"+title+"%",startIndex,pageSize);
        } catch (Exception e) {
            return null;
        }
    }

    public Integer countByTitle(String title){
        try{
            String sql = "select count(1) from article where title like ?";
            jdbcTemplate = getJdbcTemplate();
            return jdbcTemplate.queryForObject(sql, Integer.class, "%"+title+"%");
        }catch (Exception e){
            return 0;
        }
    }


    public Integer countByUserIdAndArticleId(Integer id, Integer artId) {
        try {
            String sql = "select count(1) from favorite where u_id=? and a_id=?";
            jdbcTemplate = getJdbcTemplate();
            return jdbcTemplate.queryForObject(sql,Integer.class, id, artId);
        } catch (Exception e) {
            return 0;
        }
    }

}
